package com.qf.topics;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class ProducerMain {
    public static void main(String[] args) throws IOException, TimeoutException {
        //①创建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置rabbitmq所在机器ip
        factory.setHost("localhost");
        //设置rabbitmq所在机器的程序端口号
        factory.setPort(5672);
        //设置用户名
        factory.setUsername("guest");
        //设置密码
        factory.setPassword("guest");
        //设置虚拟主机
        factory.setVirtualHost("cdm1");

        //② 利用连接工厂创建连接对象
        Connection conn = factory.newConnection();
        //③ 基于connection获取对应的channel通道对象
        Channel channel = conn.createChannel();

        //④ 发布消息（发送到交换机，由交换机分发与之绑定的队列中）
        //TOPIC路由类型，会根据消息的路由键，基于通配符匹配的形式，分发到对应的队列上
        channel.exchangeDeclare("topicEx",BuiltinExchangeType.TOPIC);

        channel.queueDeclare("topicQue1",true,false,false,null);
        channel.queueDeclare("topicQue2",true,false,false,null);

        //回头发送消息时，
        channel.queueBind("topicQue1","topicEx","A.*"); //* 表示有且只有1个单词
        //回头发送消息时，
        channel.queueBind("topicQue2","topicEx","A.#"); //# 表示0或者任意多个单词

        channel.basicPublish("topicEx","A",null,"路由消息-键A 11".getBytes(StandardCharsets.UTF_8));
        channel.basicPublish("topicEx","A.aaa",null,"路由消息-键A.aaa 11".getBytes(StandardCharsets.UTF_8));
        channel.basicPublish("topicEx","A.aaa.bb",null,"路由消息-键A.aaa.bb 22".getBytes(StandardCharsets.UTF_8));

        //⑤ 释放资源
        channel.close();
        conn.close();
    }
}
